package com.hq.zb.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hq.zb.dto.Attachment;
import com.hq.zb.exception.BizException;
import com.hq.zb.exception.BizExceptionEnum;
import com.hq.zb.mapper.AttachmentMapper;
import com.hq.zb.model.Code;
import com.hq.zb.service.IAttachmentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.Action;

/**
 * <p>
 * 附件表 服务实现类
 * </p>
 *
 * @author huanghanrui
 * @since 2022-03-27
 */
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements IAttachmentService {

    @Value("${oss.qiniu.domainPicture}")
    public String url;
    @Value("${oss.qiniu.accessKey}")
    private  String accessKey;      //类似账号，在七牛云个人空间---密钥管理获取
    @Value("${oss.qiniu.secretKey}")
    private  String accessSecretKey;   //类似密码
    // 要上传的空间
    @Value("${oss.qiniu.bucketPictureName}")
    private String bucketPictureName;
    @Autowired
    private AttachmentMapper attachmentMapper;

    @Override
    public String upload(MultipartFile file, String fileName, Attachment attachment) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huabei());  //根据自己的对象空间的地址选（华为）
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传 (个人存储空间名字)
        String bucket = bucketPictureName;
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            //记录附件表
            attachment.setAttachmentName(fileName);
            attachment.setUrl(url + fileName);
            attachmentMapper.insert(attachment);
            return url + fileName;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public void deleteAttachment(Attachment attachment) {
        Wrapper<Attachment> wrapper = new EntityWrapper<>();
        wrapper.eq("business_id", attachment.getBusinessId());
        attachmentMapper.delete(wrapper);
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.huabei());  //根据自己的对象空间的地址选（华为）
        String key = attachment.getAttachmentName();
        Auth auth = Auth.create(accessKey, accessSecretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucketPictureName, key);
        } catch (QiniuException ex) {
            throw new BizException(BizExceptionEnum.DATA_ERROR, ex.getMessage());
        }
    }
}
